//
//  HardwareViewController.m
//  StormWatch
//
//  Created by 王岩 on 2024/8/30.
//

#import "HardwareViewController.h"
#import "BleScanCollectionViewCell.h"
#import "BleConnectedCell.h"
#import "BleControlViewController.h"
#import "BleOTAViewController.h"
#import "DevicesCollectionHeaderView.h"

#import "SportRecordTable+CoreDataClass.h"
#import "OxygenTable+CoreDataClass.h"
#import "BaseInfoTable+CoreDataClass.h"
#import "BluetoothDevicesTable+CoreDataClass.h"
#import "HeartTable+CoreDataClass.h"
#import "SleepTable+CoreDataClass.h"
#import "FRIDefine.h"
#import "LocationManager.h"
#import <SVProgressHUD.h>
@interface HardwareViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, FRQBluetoothManagerDelegate>
@property (nonatomic, strong) UICollectionView * collectionView, *scanCollectionView;
@property (nonatomic, strong) NSMutableArray<BluetoothDevicesTable *> * dbDataArr;
/// 存放扫描到的 已连接过的设备
@property (nonatomic, strong) NSMutableArray<CBPeripheral *> * connectedDataArr;
/// 存放扫描到的 未连接过的设备
@property (nonatomic, strong) NSMutableArray<CBPeripheral *> * ScanDataArr;
@property (nonatomic, strong) UIImageView  * logoView;
@property (nonatomic, strong) UILabel * pageNameLab, *connectedLab, *addBlelab;
@property (nonatomic, strong) UIButton * scanBtn;
@property (nonatomic, strong) NSManagedObjectContext * context;
@property (nonatomic, strong) CBPeripheral *  peripheral;

@end

@implementation HardwareViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
//    if ([FRQBluetoothManager shareManager].curPeripheral == nil) {
        [self startScanBle];
//    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTheme) name:@"k_change_theme" object:nil];
    
    [[FRQBluetoothManager shareManager] addBleDelegate:self];
    
    [self initData];
    
    [self initUI];
    
    [self updateTheme];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disConnectBle) name:FRINotificationAtDidDisconnectPeripheral object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PoweredOff:) name:FRINotificationAtCentralManagerDidUpdateState object:nil];

    if (![FRQBluetoothManager shareManager].curPeripheral) {
        NSArray * arr = [[FRQBluetoothManager shareManager] scanPhoneConnectPeripherals];
        BOOL ha = NO;
        for (CBPeripheral* peripheral in arr)
        {
            if ([peripheral.identifier.UUIDString isEqualToString:[[NSUserDefaults standardUserDefaults] valueForKey:@"lastconnectuuid"]]) {
                ha = YES;
                peripheral.macAddress = [[NSUserDefaults standardUserDefaults] valueForKey:peripheral.identifier.UUIDString];
                self.peripheral = peripheral;
                [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:self.peripheral];
                NSLog(@"😄😄😄😄😄 第一处");
            }
        }
        if (arr.count > 0) {
            self.peripheral = arr.firstObject;
            [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:self.peripheral];
            ha = YES;
        }
        if (!ha) {
            [[FRQBluetoothManager shareManager] scanPeripherals];
        }
    }
    // Do any additional setup after loading the view.
}
- (void)initData {
    self.context = [[DBManager sharedManager] managedObjectContext];
       
    NSFetchRequest *  request = [[NSFetchRequest alloc] initWithEntityName:@"BluetoothDevicesTable"];
    NSArray<BluetoothDevicesTable *> * result = [self.context executeFetchRequest:request error:nil];
    for (BluetoothDevicesTable * tb in result) {
        if ([FRQBluetoothManager shareManager].curPeripheral && [tb.uuidstring isEqualToString:[FRQBluetoothManager shareManager].curPeripheral.identifier.UUIDString]) {
            tb.state = CBPeripheralStateConnected;
        }else {
            tb.state = CBPeripheralStateDisconnected;
        }
    }
    [self.dbDataArr addObjectsFromArray:result];

}

- (void)disConnectBle {
    DDLogDebug(@"收到通知 -- 设备断开");
    [SVProgressHUD dismiss];
    for (BluetoothDevicesTable * tb in self.dbDataArr) {
        tb.state = CBPeripheralStateDisconnected;
    }
    [self.collectionView reloadData];
//    [self.ScanDataArr removeAllObjects];
    [self.scanCollectionView reloadData];
    [FRQBluetoothManager shareManager].ready = NO;
}
- (void)PoweredOff:(NSNotification *)noti {
    NSDictionary * dic = noti.object;
    CBCentralManager * manager = dic[@"central"];
    if (manager.state == CBManagerStatePoweredOff) {
        DDLogDebug(@"收到通知 -- 蓝牙关闭");
        [self disConnectBle];
        FRQBluetoothManager.shareManager.curPeripheral = nil;
    }
}

- (void)startScanBle {
    if ([FRQBluetoothManager shareManager].curPeripheral == nil && [FRQBluetoothManager shareManager].userDisconnect == NO) {
        NSArray * arr = [[FRQBluetoothManager shareManager] scanPhoneConnectPeripherals];
        DDLogDebug(@"获取已连接的设备 数量 %d",(int)[arr count]);
        BOOL ha = NO;
        for (CBPeripheral* peripheral in arr)
        {
            if ([peripheral.identifier.UUIDString isEqualToString:[[NSUserDefaults standardUserDefaults] valueForKey:@"lastconnectuuid"]]) {
                ha = YES;
                //            peripheral.macAddress = [[NSUserDefaults standardUserDefaults] valueForKey:peripheral.identifier.UUIDString];
                self.peripheral = peripheral;
                [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:self.peripheral];
            }
        }
        if (!ha && arr.count > 0) {
            self.peripheral = arr.firstObject;
            [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:self.peripheral];
            ha = YES;
        }
        if (!ha) {
            [[FRQBluetoothManager shareManager] scanPeripherals];
        }
    }
    
    [[FRQBluetoothManager shareManager] scanPeripherals];
    
    NSArray * arr = [[FRQBluetoothManager shareManager] scanPhoneConnectPeripherals];
    for (CBPeripheral* peripheral in arr)
    {
        peripheral.macAddress = [[NSUserDefaults standardUserDefaults] valueForKey:peripheral.identifier.UUIDString];
        BOOL ha = NO;
        for (BluetoothDevicesTable * p  in self.dbDataArr) {
            if ([peripheral.identifier.UUIDString isEqualToString:p.uuidstring]) {
                [self.connectedDataArr addObject:peripheral];
                ha = YES;
            }
        }
        if (!ha) {
            [self.ScanDataArr addObject:peripheral];
        }
    }
}

- (void)initUI {
    
    [self.view addSubview:self.collectionView];
    
    _pageNameLab = [SWInitializer jy_initLabelWithText:LocalizedString(@"tab_watch") textColor:[ThemeManager sharedInstance].textColor font:S_bfont(18) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(10);
        kMakeTV(kStatusBarHeight);
        kMakeHV(44);
    }];
    
    _logoView = [SWInitializer jy_initImageViewWithImage:nil on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeRV(-10);
        kMakeTV(kStatusBarHeight + 20);
        kMakeWHV(80,80);
    }];
    
    _connectedLab = [SWInitializer jy_initLabelWithText:SWString(@"Connected devices") textColor:[ThemeManager sharedInstance].textColor font:S_font(18) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(10);
        kMakeT(self.pageNameLab.mas_bottom).offset(10);
        kMakeHV(35);
    }];
    
    _addBlelab = [SWInitializer jy_initLabelWithText:SWString(@"Add device") textColor:[ThemeManager sharedInstance].textColor font:S_font(18) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(10);
        kMakeCenterYV(0);
        kMakeHV(35);
    }];
    
    [self.view addSubview:self.scanCollectionView];
    [self.scanCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        kMakeLV(10);
        kMakeRV(-10);
        kMakeT(self.addBlelab.mas_bottom).offset(10);
        kMakeBV(-kHomeIndicatorHeight);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        kMakeLV(10);
        kMakeWV(200);
        kMakeT(self.connectedLab.mas_bottom).offset(10);
        kMakeB(self.addBlelab.mas_top).offset(-10);
    }];
}

- (void)updateTheme {
    
    self.pageNameLab.text = LocalizedString(@"tab_watch") ;
    self.connectedLab.text = SWString(@"Connected devices");
    self.addBlelab.text = SWString(@"Add device");
    
    self.view.backgroundColor = [ThemeManager sharedInstance].themeColor;
    self.pageNameLab.textColor = self.connectedLab.textColor = self.addBlelab.textColor = [ThemeManager sharedInstance].textColor;
    if (ThemeManager.sharedInstance.themeValue == Theme_Default) {
        self.logoView.image = S_imageNamed(@"logo_static");
    }else {
        self.logoView.image = S_imageNamed(@"logo_white");
    }
    [self.scanCollectionView reloadData];
    [self.collectionView reloadData];
}

- (void)bindWatch {
    [SVProgressHUD show];
    DDLogDebug(@"发送绑定指令");
    [StormCommandTool.sharedInstance writeStormCommand:Command_Bind Value:@[@0,@0,@0,@0] reBack:^(NSString * _Nonnull backData) {
        if (!backData) {
            return;
        }
        if (backData && [backData hasSuffix:@"0101000100"]) {
            [FRQBluetoothManager shareManager].ready = YES;
            DDLogDebug(@"绑定成功");
            [self readCurrentData];
        }else {
            [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:[FRQBluetoothManager shareManager].curPeripheral];
            [SVProgressHUD dismiss];
        }
    }];
}

- (void)readCurrentData {
    DDLogDebug(@"开始读取 蓝牙数据 ");
    [[StormCommandTool sharedInstance] updateDateAndTimeCallBack:^(BOOL success) {
        if (success) {
            DDLogDebug(@"开始读取目标步数");
            [[StormCommandTool sharedInstance] readStepTargetData:^(BOOL success, unsigned long stepData) {
                if (success) {
                    [[NSUserDefaults standardUserDefaults] setValue:@(stepData) forKey:@"Storm_steptarget"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        DDLogDebug(@"开始读取 实时数据");
                        [[StormCommandTool sharedInstance] readRealTimeData:^(BOOL success, unsigned long stepData, unsigned long caloriesData, unsigned long distanceData, unsigned long heartRateData, unsigned long electricData) {
                            [SVProgressHUD dismiss];
                            DDLogDebug(@"开始更新天气，loading 消失");
                            [[LocationManager sharedInstance] startUpdateLocation];
                        }];
                    });
                }else {
                    [SVProgressHUD dismiss];
                }
            }];
        }else {
            [SVProgressHUD dismiss];
        }
       
    }];
}


- (void)deleteLocalData:(BluetoothDevicesTable * )ble  {
    
    NSString *uuid = ble.uuidstring;
    
    if ([uuid isEqualToString:[[NSUserDefaults standardUserDefaults] valueForKey:@"lastconnectuuid"]]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"lastconnectuuid"];
    }
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSFetchRequest *  request = [[NSFetchRequest alloc] initWithEntityName:@"BluetoothDevicesTable"];
        NSPredicate * predicate = [NSPredicate predicateWithFormat:@"uuidstring = %@",uuid];
        request.predicate = predicate;
        NSArray<BluetoothDevicesTable *> * result = [self.context executeFetchRequest:request error:nil];
        [result enumerateObjectsUsingBlock:^(BluetoothDevicesTable * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.context deleteObject:obj];
        }];
        [[DBManager sharedManager] saveContext];
        
        NSPredicate * predicate2 = [NSPredicate predicateWithFormat:@"deviceUUID = %@",uuid];
        
        NSFetchRequest *  request2 = [[NSFetchRequest alloc] initWithEntityName:@"SportRecordTable"];
        request2.predicate = predicate2;
        NSArray<SportRecordTable *> * result2 = [self.context executeFetchRequest:request2 error:nil];
        [result2 enumerateObjectsUsingBlock:^(SportRecordTable * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.context deleteObject:obj];
        }];
        [[DBManager sharedManager] saveContext];
        
        NSFetchRequest *  request3 = [[NSFetchRequest alloc] initWithEntityName:@"OxygenTable"];
        request3.predicate = predicate2;
        NSArray<OxygenTable *> * result3 = [self.context executeFetchRequest:request3 error:nil];
        [result3 enumerateObjectsUsingBlock:^(OxygenTable * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.context deleteObject:obj];
        }];
        [[DBManager sharedManager] saveContext];
        
        NSFetchRequest *  request4 = [[NSFetchRequest alloc] initWithEntityName:@"BaseInfoTable"];
        request4.predicate = predicate2;
        NSArray<BaseInfoTable *> * result4 = [self.context executeFetchRequest:request4 error:nil];
        [result4 enumerateObjectsUsingBlock:^(BaseInfoTable * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.context deleteObject:obj];
        }];
        [[DBManager sharedManager] saveContext];
        
        NSFetchRequest *  request5 = [[NSFetchRequest alloc] initWithEntityName:@"HeartTable"];
        request5.predicate = predicate2;
        NSArray<HeartTable *> * result5 = [self.context executeFetchRequest:request5 error:nil];
        [result5 enumerateObjectsUsingBlock:^(HeartTable * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.context deleteObject:obj];
        }];
        [[DBManager sharedManager] saveContext];
        
        NSFetchRequest *  request6 = [[NSFetchRequest alloc] initWithEntityName:@"SleepTable"];
        request6.predicate = predicate2;
        NSArray<SleepTable *> * result6 = [self.context executeFetchRequest:request6 error:nil];
        [result6 enumerateObjectsUsingBlock:^(SleepTable * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.context deleteObject:obj];
        }];
        
        [[DBManager sharedManager] saveContext];
    });
    
    [self.dbDataArr removeObject:ble];
    [self.collectionView reloadData];
    
}

#pragma mark -- FRQBluetoothManagerDelegate
-(void)onBLEManagerDiscoverPeripheral:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral advertisement:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    BOOL ha = NO;
    for (CBPeripheral * per in self.ScanDataArr) {
        if ([peripheral.identifier.UUIDString isEqualToString:per.identifier.UUIDString]) {
            ha = YES;
        }
    }
    if (!ha) {
        ha = NO;
        for (BluetoothDevicesTable * device in self.dbDataArr) {
            if ([peripheral.identifier.UUIDString isEqualToString:device.uuidstring]) {
                ha = YES;
            }
        }
        if (!ha) {
            DDLogDebug(@"onBLEManagerDiscoverPeripheral  发现未连接过的蓝牙设备");
            [self.ScanDataArr addObject:peripheral];
            [self.scanCollectionView reloadData];
        }else {
            DDLogDebug(@"onBLEManagerDiscoverPeripheral  发现已连接过的蓝牙设备");
            if (![self.connectedDataArr containsObject:peripheral]) {
                [self.connectedDataArr addObject:peripheral];
            }
        }
    }
}

-(void)onBLEManagerConnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error{
 
    if ([self.ScanDataArr containsObject:peripheral]) {
        [self.connectedDataArr addObject:peripheral];
        [self.ScanDataArr removeObject:peripheral];
        DDLogDebug(@"onBLEManagerConnect  未连接过的设备 连接成功");

        BluetoothDevicesTable * dev = [NSEntityDescription insertNewObjectForEntityForName:@"BluetoothDevicesTable" inManagedObjectContext:self.context];
        dev.uuidstring = peripheral.identifier.UUIDString;
        dev.name = peripheral.name;
        dev.state = 2;
        
        [self.dbDataArr insertObject:dev atIndex:0];
        
        [[DBManager sharedManager] saveContext];
    }else {
        for (BluetoothDevicesTable * da in self.dbDataArr) {
            if ([peripheral.identifier.UUIDString isEqualToString:da.uuidstring]) {
                da.state = 2;
                DDLogDebug(@"onBLEManagerConnect  已连接过的设备 连接成功");
            }
        }
    }
    
    [self.collectionView reloadData];
    [self.scanCollectionView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        if (!peripheral.ancsAuthorized) {
//            [[FRQBluetoothManager shareManager] sendCommandData:[@"54590100" mj_JSONData] completion:^(NSString * _Nonnull resultString) {
//                
//            }];
//        }
    });
    [FRQBluetoothManager shareManager].userDisconnect = NO;
}

- (void)onBLEManagerReady:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        DDLogDebug(@"onBLEManagerReady  准备读取数据");
        [self bindWatch];
    });
}

#pragma mark --  CollectionDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.collectionView == collectionView) {
        return 1;
    }
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.collectionView == collectionView) {
        return self.dbDataArr.count   ;
    }
    if (section == 0) {
        return self.ScanDataArr.count;
    }
    return 0;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.collectionView) {
        BleConnectedCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BleConnectedCell" forIndexPath:indexPath];
        BluetoothDevicesTable * p = self.dbDataArr[indexPath.row];
        if (p.state == CBPeripheralStateConnecting) {
            cell.stateLab.text = SWString(@"Connecting");
            cell.stateLab.textColor = S_HexColor(@"#DF660F");
            cell.stateView.backgroundColor = [S_HexColor(@"#E5810C") colorWithAlphaComponent:0.5];;
            cell.iconView.image = S_imageNamed(@"icon_history_device_unconnect");
        }else if (p.state == CBPeripheralStateConnected) {
            cell.stateLab.text = SWString(@"Connected");
            cell.stateLab.textColor = S_HexColor(@"#95D46F");
            cell.stateView.backgroundColor = [S_HexColor(@"#95D46F") colorWithAlphaComponent:0.5];
            cell.iconView.image = S_imageNamed(@"icon_history_device_connect");
        }else {
            cell.stateLab.text = SWString(@"Unconnected");
            cell.stateLab.textColor = S_HexColor(@"#CACACA");
            cell.stateView.backgroundColor = [S_HexColor(@"#CACACA") colorWithAlphaComponent:0.5];
            cell.iconView.image = S_imageNamed(@"icon_history_device_unconnect");
        }
        cell.deleteBlock = ^{
            NSArray * arr = [[NSUserDefaults standardUserDefaults] valueForKey:@"firstconnectdevices"];
            if ([arr containsObject:FRQBluetoothManager.shareManager.curPeripheral.identifier.UUIDString]) {
                NSMutableArray * mut = [[NSMutableArray alloc] initWithArray:arr];
                [mut removeObject:FRQBluetoothManager.shareManager.curPeripheral.identifier.UUIDString];
                [[NSUserDefaults standardUserDefaults] setValue:mut forKey:@"firstconnectdevices"];
                
            }
            if ([[FRQBluetoothManager shareManager].curPeripheral.identifier.UUIDString isEqualToString:p.uuidstring]) {
//                [StormCommandTool.sharedInstance writeStormCommand:Command_unBind Value:@[@0,@0,@0,@0] reBack:^(NSString * _Nonnull backData) {
                    [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:[FRQBluetoothManager shareManager].curPeripheral];
//                }];
            }
            [self deleteLocalData:p];

        };
        if (ThemeManager.sharedInstance.themeValue == Theme_Default) {
            cell.nameLab.textColor = [UIColor blackColor];
        }else {
            cell.nameLab.textColor = [UIColor whiteColor];
        }
        return cell;
    }else {
        BleScanCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BleScanCollectionViewCell" forIndexPath:indexPath];
        CBPeripheral * p = self.ScanDataArr[indexPath.row];
        [cell setMacAddress:p.macAddress];
        if (ThemeManager.sharedInstance.themeValue == Theme_Default) {
            cell.nameLab.textColor = [UIColor blackColor];
        }else {
            cell.nameLab.textColor = [UIColor whiteColor];
        }
        return cell;
    }
   
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView == self.collectionView) {
        DDLogDebug(@"didSelectItemAtIndexPath 点击已连接过的设备");
        BluetoothDevicesTable * da = self.dbDataArr[indexPath.row];
        if (da.state == 2 && [[FRQBluetoothManager shareManager].curPeripheral.identifier.UUIDString isEqualToString:da.uuidstring]) {
            DDLogDebug(@"didSelectItemAtIndexPath 点击当前连接中的设备");
            BleControlViewController * vc = [[BleControlViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            if (da.state == 0) {
                DDLogDebug(@"点击已连接过的设备，设备状态:未连接");
            }else  if (da.state == 1) {
                DDLogDebug(@"点击已连接过的设备，设备状态:连接中");
            }else if (da.state == 2) {
                DDLogDebug(@"点击已连接过的设备，设备状态:已连接");
            }else {
                DDLogDebug(@"点击已连接过的设备，设备状态:未知");
            }
            
            if ([FRQBluetoothManager shareManager].curPeripheral) {
                [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:[FRQBluetoothManager shareManager].curPeripheral];
            }
            
            CBPeripheral *  peripheral = nil;
            for (CBPeripheral * p  in self.connectedDataArr) {
                if ([p.identifier.UUIDString isEqualToString:da.uuidstring]) {
                    peripheral = p;
                    break;
                }
            }
            if (peripheral) {
                da.state = 1;
                [self.collectionView reloadData];
//                [[FRQBluetoothManager shareManager] cancelScan];
                NSLog(@"😄😄😄😄😄 第3处");
                DDLogDebug(@"didSelectItemAtIndexPath 点击设备开始连接");
                [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:peripheral];
                
            }else{
                toast(@"No Find");
                DDLogDebug(@"didSelectItemAtIndexPath 点击设备  未找到");
            }
        }
       
    }else {
        CBPeripheral * p = self.ScanDataArr[indexPath.row];
        [[FRQBluetoothManager shareManager] cancelScan];
        if ([FRQBluetoothManager shareManager].curPeripheral) {
            [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:[FRQBluetoothManager shareManager].curPeripheral];
        }
        DDLogDebug(@"didSelectItemAtIndexPath 点击未连接的设备");
//        [[FRQBluetoothManager shareManager] connectToPeripheral:p];
        [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:p];
       
        [self.scanCollectionView reloadData];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (collectionView == self.scanCollectionView) {
        return CGSizeMake(kScreenWidth, 40);
    }
    return CGSizeZero;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.scanCollectionView) {
        if (kind == UICollectionElementKindSectionHeader ) {
            DevicesCollectionHeaderView * view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"DevicesCollectionHeaderView" forIndexPath:indexPath];
            if (indexPath.section == 0) {
                view.nameLab.text = SWString(@"Automatically add devices");
            }else {
                view.nameLab.text = SWString(@"Manually add devices");
            }
            view.nameLab.textColor = ThemeManager.sharedInstance.textColor;
            
            return view;
        }
        return nil;
    }
    return nil;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.itemSize = CGSizeMake(200, 60);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, kNavigationBarHeight, 200, 400) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerNib:[UINib nibWithNibName:@"BleScanCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"BleScanCollectionViewCell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"BleConnectedCell" bundle:nil] forCellWithReuseIdentifier:@"BleConnectedCell"];
    }
    return _collectionView;
}

- (UICollectionView *)scanCollectionView {
    if (!_scanCollectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.itemSize = CGSizeMake((kScreenWidth - 32) / 2, 60);
        _scanCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, kNavigationBarHeight, kScreenWidth - 20, 400) collectionViewLayout:layout];
        _scanCollectionView.delegate = self;
        _scanCollectionView.dataSource = self;
        _scanCollectionView.backgroundColor = [UIColor clearColor];
        [_scanCollectionView registerNib:[UINib nibWithNibName:@"BleScanCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"BleScanCollectionViewCell"];
        [_scanCollectionView registerClass:[DevicesCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"DevicesCollectionHeaderView"];
    }
    return _scanCollectionView;
}

- (NSMutableArray<BluetoothDevicesTable *> *)dbDataArr{
    if (!_dbDataArr) {
        _dbDataArr = [[NSMutableArray alloc] init];
    }
    return _dbDataArr;
}

- (NSMutableArray<CBPeripheral *> *)ScanDataArr {
    if (!_ScanDataArr) {
        _ScanDataArr = [[NSMutableArray alloc] init];
    }
    return _ScanDataArr;
}
- (NSMutableArray<CBPeripheral *> *)connectedDataArr{
    if (!_connectedDataArr) {
        _connectedDataArr = [[NSMutableArray alloc] init];
    }
    return _connectedDataArr;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
